<template>
  <div class="config-table-container">
    <!-- 标题和操作按钮区域 -->
    <div class="header-container">
      <h2>配置项管理</h2>
      <el-button type="primary" size="small" @click="handleAddConfig">添加配置项</el-button>
    </div>

    <!-- 配置项表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%; background-color: transparent !important;"
      v-loading="loading"
      element-loading-text="正在加载配置项..."
      element-loading-background="rgba(255, 255, 255, 0.8)"
      element-loading-custom-class="custom-loading"
      :border="false"
      :show-header="true"
      :cell-style="{backgroundColor: 'transparent', border: 'none'}"
      :header-cell-style="{backgroundColor: 'transparent', border: 'none'}"
      class="transparent-table"
    >
      <!-- ID列 -->
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      
      <!-- 配置项名称列 -->
      <el-table-column prop="dispose_name" label="配置项名称" min-width="150" align="center"></el-table-column>
      
      <!-- 配置项值列 -->
      <el-table-column prop="dispose_item" label="配置项" min-width="180" align="center"></el-table-column>
      
      <!-- 编辑时间列 -->
      <el-table-column prop="create_time" label="编辑时间" width="180" align="center"></el-table-column>
      
      <!-- 备注列 -->
      <el-table-column prop="notes" label="备注" min-width="180" align="center"></el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button 
            type="primary" 
            size="mini" 
            icon="el-icon-edit" 
            @click="handleEdit(scope.row)"
            circle>
          </el-button>
          <el-button 
            type="danger" 
            size="mini" 
            icon="el-icon-delete" 
            @click="handleDelete(scope.row)"
            circle>
          </el-button>
        </template>
      </el-table-column>
      <!-- 添加空状态插槽 -->
      <template slot="empty">
        <empty-state />
      </template>
    </el-table>
    
    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑配置项对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="460px">
      <el-form :model="form" :rules="rules" ref="configForm" label-width="120px">
        <el-form-item label="ID" v-if="isEdit">
          <el-input v-model="form.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="配置项名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入配置项名称"></el-input>
        </el-form-item>
        <el-form-item label="配置项" prop="configValue">
          <el-input v-model="form.configValue" placeholder="请输入配置项"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false" :disabled="submitLoading">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import EmptyState from './EmptyState.vue'

// 设置全局超时时间为20秒
axios.defaults.timeout = 20000;

export default {
  name: 'ConfigTable',
  components: {
    EmptyState
  },
  data() {
    return {
      loading: false,
      submitLoading: false,
      tableData: [], // 当前页显示的数据
      allData: [],  // 保存所有数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '添加配置项',
      isEdit: false,
      form: {
        id: '',
        configName: '',
        configValue: '',
        editTime: '',
        remarks: ''
      },
      rules: {
        configName: [
          { required: true, message: '请输入配置项名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        configValue: [
          { required: true, message: '请输入配置项', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取配置项数据
    fetchData() {
      // 确保设置loading状态
      this.loading = true;
      
      axios.get('/api/get_project_configs/')
        .then(response => {
          if (response.data.code === 200) {
            // 保存所有数据
            this.allData = Array.isArray(response.data.data) ? response.data.data : [];
            this.total = this.allData.length;
            
            // 更新当前页数据
            this.updatePageData();
          } else {
            this.$message.error(response.data.msg || '获取配置项失败');
            this.allData = [];
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error('获取配置项失败:', error);
          this.$message.error('获取配置项失败，请稍后重试!');
          this.allData = [];
          this.tableData = [];
          this.total = 0;
        })
        .finally(() => {
          // 请求完成后，无论成功或失败，都关闭loading
          this.loading = false;
          // 如果是在提交表单后获取的数据，也需要关闭submitLoading
          if (this.submitLoading) {
            this.submitLoading = false;
          }
        });
    },

    // 更新当前页数据
    updatePageData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.allData.slice(start, end);
    },
    
    // 处理页面大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      // 更新当前页数据
      this.updatePageData();
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      // 更新当前页数据
      this.updatePageData();
    },
    
    // 添加配置项
    handleAddConfig() {
      this.dialogTitle = '添加配置项';
      this.isEdit = false;
      this.form = {
        id: '',
        configName: '',
        configValue: '',
        editTime: '',
        remarks: ''
      };
      this.dialogVisible = true;
    },
    
    // 编辑配置项
    handleEdit(row) {
      this.dialogTitle = '编辑配置项';
      this.isEdit = true;
      this.form = {
        id: row.id,
        configName: row.dispose_name,
        configValue: row.dispose_item,
        remarks: row.notes || ''
      };
      this.dialogVisible = true;
    },
    
    // 删除配置项
    handleDelete(row) {
      this.$confirm('确认删除该配置项吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        axios.post('/api/delete_project_config/', {
          id: row.id,
          dispose_name: row.dispose_name
        })
          .then(response => {
            if (response.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              // 保持loading状态，通过fetchData最终会设置loading为false
              this.fetchData();
            } else {
              this.$message({
                type: 'error',
                message: response.data.message || '删除失败!'
              });
              this.loading = false; // 出错时手动关闭loading
            }
          })
          .catch(error => {
            console.error('删除配置项失败:', error);
            this.$message({
              type: 'error',
              message: '删除失败，请稍后重试!'
            });
            this.loading = false; // 出错时手动关闭loading
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.configForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          if (this.isEdit) {
            // 编辑模式，更新现有配置项
            axios.post('/api/update_project_config/', {
              id: this.form.id,
              dispose_name: this.form.configName,
              dispose_item: this.form.configValue,
              notes: this.form.remarks || ''
            })
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success(response.data.msg || '更新成功!');
                  this.dialogVisible = false;
                  this.loading = true; // 保持loading状态
                  this.fetchData(); // 获取最新数据
                } else {
                  this.$message.error(response.data.msg || '更新失败!');
                  this.submitLoading = false;
                }
              })
              .catch(error => {
                console.error('更新配置项失败:', error);
                this.$message.error('更新失败，请稍后重试!');
                this.submitLoading = false;
              });
          } else {
            // 添加模式，创建新配置项
            axios.post('/api/create_project_config/', {
              dispose_name: this.form.configName,
              dispose_item: this.form.configValue,
              notes: this.form.remarks || ''
            })
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success(response.data.msg || '添加成功!');
                  this.dialogVisible = false;
                  this.loading = true; // 保持loading状态
                  this.fetchData(); // 获取最新数据
                } else {
                  this.$message.error(response.data.msg || '添加失败!');
                  this.submitLoading = false;
                }
              })
              .catch(error => {
                console.error('添加配置项失败:', error);
                this.$message.error('添加失败，请稍后重试!');
                this.submitLoading = false;
              });
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.config-table-container {
  padding: 20px 0;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 30px;
}

.header-container h2 {
  margin: 0;
  color: #303133;
}

.pagination-container {
  margin-top: 10px;
  text-align: center;
  padding: 10px;
}

/* 移除表格所有边框和背景色 */
.transparent-table.el-table {
  background-color: transparent !important;
}

.transparent-table.el-table::before,
.transparent-table.el-table::after {
  display: none;
}

.transparent-table.el-table .el-table__header-wrapper,
.transparent-table.el-table .el-table__body-wrapper {
  background-color: transparent !important;
}

.transparent-table.el-table .el-table__header th.el-table__cell {
  background-color: transparent !important;
  border: none !important;
}

.transparent-table.el-table .el-table__body td.el-table__cell {
  background-color: transparent !important;
  border: none !important;
}

.transparent-table.el-table .el-table__body tr:hover > td.el-table__cell {
  background-color: transparent !important;
}

.transparent-table.el-table .el-table__body tr.hover-row > td.el-table__cell {
  background-color: transparent !important;
}

.transparent-table.el-table .el-table__body tr.el-table__row--striped > td.el-table__cell {
  background-color: transparent !important;
}

.page-info {
  margin-left: 15px;
  color: #606266;
  font-size: 13px;
}
</style>

<!-- 添加全局样式 -->
<style>
/* 自定义加载样式 */
.custom-loading .el-loading-spinner .circular {
  display: none !important;
}

.custom-loading .el-loading-spinner::before {
  content: '';
  display: block;
  width: 50px;
  height: 50px;
  background: url(../assets/loading.png) no-repeat center center;
  background-size: contain;
  animation: rotate 1.5s linear infinite;
  margin: 0 auto;
}

/* 自定义加载文字样式 */
.custom-loading .el-loading-spinner .el-loading-text {
  color: #000000 !important; /* 黑色文字 */
  margin-top: 10px !important; /* 与图标保持10px距离 */
  font-size: 14px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
